﻿using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.Jobs;

public class JobSystem3 : MonoBehaviour {
    TransformAccessArray m_TransformsAccessArray;
    public int count;
    public float radius;

    Transform[] trans;

    Job3 m_PositionJob;

    JobHandle m_PositionJobHandle;

    // Use this for initialization
    void Start () {
        trans = new Transform[count];
        GameObject[] objs = PlaceRandomCubes(count, radius);
        for (int i = 0; i < objs.Length; i++) {
            trans[i] = objs[i].GetComponent<Transform>();
        }

        m_TransformsAccessArray = new TransformAccessArray(trans);
	}
	
	// Update is called once per frame
	void Update () {
        m_PositionJob = new Job3() {
            time = Time.deltaTime*30,
        };

        m_PositionJobHandle = m_PositionJob.Schedule(m_TransformsAccessArray);
    }

    public void LateUpdate() {
        m_PositionJobHandle.Complete();
    }

    private void OnDestroy() {
        m_TransformsAccessArray.Dispose();
    }

    public GameObject[] PlaceRandomCubes(int count, float radius) {
        var cubes = new GameObject[count];
        var cubeToCopy = MakeStrippedCube();

        for (int i = 0; i < count; i++) {
            var cube = GameObject.Instantiate(cubeToCopy);
            cube.transform.position = UnityEngine.Random.insideUnitSphere * radius;
            cubes[i] = cube;
        }

        GameObject.Destroy(cubeToCopy);

        return cubes;
    }

    public GameObject MakeStrippedCube() {
        var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        //turn off shadows entirely
        var renderer = cube.GetComponent<MeshRenderer>();
        renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        renderer.receiveShadows = false;

        // disable collision
        var collider = cube.GetComponent<Collider>();
        collider.enabled = false;

        return cube;
    }
}

public struct Job3 : IJobParallelForTransform {
    public float time;
    public void Execute(int index, TransformAccess transform) {
        transform.position = Quaternion.AngleAxis(time, Vector3.up) * transform.position;
    }
}
